$(function() {
	$.fn.raty.defaults.path = rootPath+'/statics/images';
	//$('#default-demo').raty();
	$("div[name='default-demo']").each(function(){
		$(this).raty();
	});
	$("textarea[name='content']").each(function(){
		$(this).bind({
			"keyup": function (e) {
				checkWords($(this));  
			}  
		});
	});
	//加载商品图片大图浏览
	$("a[tag='productImg']").each(function(){
		var rel = $(this).attr("rel");
		initFancyBoxImg(rel);
	});
});
var urlReg ={  
	    "urlRegText":"((news|telnet|nttp|file|http|ftp|https)://){1}(([-A-Za-z0-9]+(\\.[-A-Za-z0-9]+)*(\\.[-A-Za-z]{2,5}))|([0-9]{1,3}(\\.[0-9]{1,3}){3}))(:[0-9]*)?(/[-A-Za-z0-9_\\$\\.\\+\\!\\*\\(\\),;:@&=\\?/~\\#\\%]*)*"  
	};

// 字符串长度
function smartLen(str) {  
    str = str.replace(/(^[\s\n]+)|([\s\n]+$)/,"").replace(/[\s\n]+/g," ");
    str = str.replace(new RegExp(urlReg.urlRegText, "gi"), new Array(12).join("aa"));
    return Math.ceil($.trim(str).length);
//	return Math.ceil(($.trim(str.replace(/[^\u0000-\u00ff]/g, "aa")).length));
}
function checkWords(obj){
	var content = $(obj).val();
//	var len = 100-smartLen(content);
	var len = smartLen(content);
	if (len < 0) {  
        $(obj).closest("div").find("em[name='txtLen']").html(0);  
    } else {
    	$(obj).closest("div").find("em[name='txtLen']").html( len );  
    	if (len > 100) {
    		$(obj).closest("div").find("em[name='txtLen']").addClass("txt_red");
    		$("#contentLen").val("false");
    	} else {
    		$(obj).closest("div").find("em[name='txtLen']").removeClass("txt_red");
    		$("#contentLen").val("true");
    	}
    }  
}  

function uploadImg(obj) {
	$(obj).closest("div[class='upload_btn']").find("input[type='file']").click();
}

//通过ajax提交图片
function ajaxFileUpload(obj) {
	var id = $(obj).attr("id");
	var detailId = $(obj).attr("detailId");
	var check = imageCheck(obj);
	if (!check) {
		return;
	}
	$.ajaxFileUpload({
		url: rootPath + '/uploadFile/uploadOneFile',
//		url:  rootPath + "/test/upload",
		secureuri: false,
		fileElementId: id, // input标签id属性值
		dataType: 'json',
		success: function(data, status) {
			if(data.code == 1) {
				addImage(detailId, data.filePath);
				//防止连续上传同一张图片,防止取消上传出现裂图
				$("#"+id).find("input[type='file']").val("");
			} else {
				layer.msg('上传失败', {
					icon : 2,
					time : 2000
				});
			}
		},
		error: function(data, status, e) {
			layer.msg('系统异常', {
				icon : 2,
				time : 2000
			});
		}
	});
}

//检查图片格式及大小
function imageCheck(obj){
	var id = $(obj).attr("id");
	var filePath = $("#"+id).val();
	//检查后缀
	var ext = filePath.substring(filePath.lastIndexOf("."), filePath.length).toUpperCase();
	if (ext != ".BMP" && ext != ".PNG" && ext != ".GIF" && ext != ".JPG" && ext != ".JPEG") {
		layer.msg('只能上传图片',{time:500});
		return false;
	}
	var file_size = 0;
	if (false || !!document.documentMode) {
		var img = new Image();
		img.src = filepath;
		while (true) {
			if (img.fileSize > 0) {
				if (img.fileSize > 5 * 1024 * 1024) {
					layer.msg('图片不能大于5MB',{time:1000});
					return false;
				}
				break;
			}
		}
	} else {
		file_size = obj.files[0].size;
		var size = file_size / 1024;
		if (size > 5120) {
			layer.msg('图片不能大于5MB',{time:1000});
			return false;
		}
	}
	return true;
}

//填充图片及删除按钮事件
function addImage(detailId, imgPath) {
	var ul = $("#ul_"+detailId);
	$(ul).append("<li>" +
			"	<input type='hidden' name='filePath' value='"+imgPath+"'/>" +
			"	<a rel='detail_img_"+detailId+"' href='"+imgRootURL+imgPath+"'>" +
			"		<img src='"+imgRootURL+imgPath+"?x-oss-process=image/resize,m_pad,h_60,w_60'>" +
			"	</a>" +
			"	<a href='javascript:void(0);' class='icon_close'></a>" +
			" </li>");
	$(ul).find("a[class='icon_close']").each(function(){
		$(this).unbind();
		$(this).bind("click", function(){
			$(this).closest("li").remove();
		});
	});
	//加载大图浏览器
	initFancyBoxImg("detail_img_"+detailId);
}

/**
 * 提交评价
 */
function commitEvaluation() {
	var evaluationList = [];
	$("div[name='comment_div']").each(function(){
		var evaluation = new Object();
		evaluation.productCode = $(this).find("input[name='productCode']").val();
		evaluation.productName = $(this).find("input[name='productName']").val()+"<span></span>"+$(this).find("input[name='productSpec']").val();
		evaluation.imagePath = $(this).find("input[name='imagePath']").val();
		//不打分则默认好评
		var score = $(this).find("input[name='score']").val();
		if (score == "") {
			score = "5";
		}
		evaluation.score = Number(score);
		evaluation.content = $(this).find("textarea[name='content']").val();
		var filePaths = [];
		$(this).find("input[name='filePath']").each(function(){
			var filePath = $(this).val();
			filePaths.push(filePath);
		});
		evaluation.filePath = filePaths.toString();
		evaluationList.push(evaluation);
	});
	var orderCode = $("#orderCode").val();
	var contentLen = $("#contentLen").val();
	if (contentLen == "false") {
		layer.msg("评论字数过多", {icon : 2,time : 2000});
		return;
	}
	$.ajax({
		url: rootPath + "/pc/evaluation/commitEvaluation",
		data: {orderCode: orderCode, evaluationList: JSON.stringify(evaluationList)},
		type: "post",
		async: true,
		dataType: "json",
		success: function(data) {
			if(data.resultCode == '1'){
				window.location.href = rootPath + "/pc/evaluation/toEvaluationResult";
			} else {
				layer.msg(data.resultMsg, {icon : 2,time : 2000});
			}
		}
	});
//	window.location.href='评价成功.htm';
}

//加载图片浏览器
function initFancyBoxImg(relName){
	$("a[rel='"+relName+"']").fancybox({
		'titlePosition' : 'over',
		'cyclic'        : false
	});
}
